package sword.chapter8Tree;

import java.util.Stack;

/**
 * 二叉搜索树迭代器
 *
 * 方式1
 * 迭代器根据中序遍历改造
 * hasNext  最外层while循环
 * next     内层while循环，中序遍历每一个节点值
 *
 * 方式2
 * 展平二叉树（见52题），然后将指针指向第一个节点
 *
 * @author K
 * @date 2021/12/13 09:10
 */
public class S55BSTIterator {
    TreeNode cur;
    Stack<TreeNode> stack;

    public S55BSTIterator(TreeNode root) {
        cur = root;
        stack = new Stack<>();
    }

    public boolean hasNext() {
        return cur != null || !stack.isEmpty();
    }

    public int next() {
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }

        cur = stack.pop();
        int val = cur.val;
        cur = cur.right;

        return val;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);
        root.left = node2;
        root.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        S55BSTIterator iterator = new S55BSTIterator(root);
        boolean b = iterator.hasNext();
        int next = iterator.next();
        boolean b1 = iterator.hasNext();
        System.out.println();
    }
}
